package com.lagou.cl.server;

import com.lagou.cl.RequestProcessor;
import com.lagou.cl.pojo.MappedHost;
import com.lagou.cl.pojo.Mapper;
import com.lagou.cl.util.TheadPoolUtil;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;


public class ConnectorProcessor extends Thread {


	private Integer port;

	public ConnectorProcessor(Integer port) {
		this.port = port;
	}

	@Override
	public void run() {
		try {
			System.out.println("监听端口：" + this.port);
			ServerSocket serverSocket = new ServerSocket(this.port);

			while (true) {
				Socket accept = serverSocket.accept();
				MappedHost mappedHost = null;
				for (MappedHost host : Mapper.mappedHosts) {
					Integer object = host.getObject();
					if (this.port.equals(object)) {
						mappedHost = host;
						System.out.println("线程：" + Thread.currentThread().getName() + "处理端口：" + this.port + "的MappedHost：" + mappedHost.getName());
						break;
					}
				}
				if (mappedHost != null) {
					RequestProcessor processor = new RequestProcessor(accept, mappedHost);
					TheadPoolUtil.getThreadPoolExecutor().execute(processor);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
